package com.glor.operation.common.utils;

import com.glor.operation.common.DataResponse;
import com.glor.operation.common.excep.BaseException;
import com.glor.operation.common.Response;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created by heylear.cai on 2016/2/18.
 */
public class ResponseHelper {
    public static final String STATE_VIEW = "common/state";

    public static <T> Response successResp(T t) {
        DataResponse response = new DataResponse<T>();
        response.setData(t);
        return response;
    }

    public static Response infoResp(Object object) {
        Response resp = null;
        if (object instanceof DataResponse) {
            resp = (Response) object;
        } else if (object instanceof Response) {
            resp = ResponseHelper.infoResp(((Response) object).getStatus(), ((Response) object).getMessage());
        } else {
            resp = ResponseHelper.successResp(object);
        }
        return resp;
    }

    public static Response errorResp(Throwable t) {
        BaseException be;
        if (t instanceof BaseException) {
            be = (BaseException) t;
        } else {
            be = new BaseException(t.getMessage());
        }
        return infoResp(be.getErrorCode(), be.getMessage());
    }



    public static Response infoResp(int status, String message) {
        return new DataResponse(status, message);
    }

    public static ModelAndView buildView(String path, Response response) {
        ModelAndView mv = new ModelAndView(path);
        mv.getModelMap().addAttribute("status", response.getStatus());
        mv.getModelMap().addAttribute("message", response.getMessage());
        if (response instanceof DataResponse){
            mv.getModelMap().addAttribute("data", ((DataResponse) response).getData());
        }
        return mv;
    }

    public static ModelAndView buildStateView(Response response) {
        return buildView(STATE_VIEW, response);
    }

    public static ModelAndView buildStateView(Throwable t) {
        return buildStateView(errorResp(t));
    }

    public static ModelAndView buildStateView(int status, String message) {
        return buildView(STATE_VIEW, new DataResponse(status, message));
    }
}
